package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Video;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * * @title: VideoMQService
 *
 * @Author Philcan
 * @Date: 2021/8/21 14:46
 * @Version 1.0
 */
@Service
@Slf4j
public class VideoMQService {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    public Boolean videoMsg(String videoId) {
        return this.sendMsg(videoId, 1);
    }

    public Boolean likeVideoMsg(String videoId) {
        return this.sendMsg(videoId, 2);
    }

    public Boolean disLikeoMsg(String videoId) {
        return this.sendMsg(videoId, 3);
    }

    public Boolean commentVideoMsg(String videoId) {
        return this.sendMsg(videoId, 4);
    }

    /*
     * @Author Philcan
     *
     * @Date 2021/8/21 14:53
     * @Param [videoId, type]   1-发动态，2-点赞， 3-取消点赞，4-评论
     * @return java.lang.Boolean
     **/
    private Boolean sendMsg(String videoId, int type) {
        try {
            User user = UserThreadLocal.get();
            Video video = this.videoApi.queryVideoById(videoId);
            Map<String, Object> map = new HashMap<>();

            map.put("userId", user.getId());
            map.put("date", System.currentTimeMillis());
            map.put("videoId", videoId);
            map.put("vid", video.getId());
            map.put("type", type);

            this.rocketMQTemplate.convertAndSend("tanhua-video", map);
        } catch (MessagingException e) {
            log.error("发送消息失败! videoId = " + videoId + ", type = " + type, e);
            return false;
        }
        return true;
    }
}
